package com.traffic.visim.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.traffic.visim.common.CommonConstant;
import com.traffic.visim.common.Result;
import com.traffic.visim.config.TrafficConfig;
import com.traffic.visim.service.TrafficService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
@Slf4j
public class TrafficServiceImpl implements TrafficService {
    public static final String TOKEN_KEY="token_key";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrafficConfig trafficConfig;

    /***
     * 获取登录地址
     * @return
     */
    private String getUrl(){
        String ip= trafficConfig.getUrl();
        String port=trafficConfig.getPort();
        String projectName=trafficConfig.getProjectName();
        String url= "http://" +ip+":"+port+"/"+projectName+"/";
        return url;
    }

    @Override
    public String getToken() throws  Exception{
        String userName=trafficConfig.getUserName();
        String password=trafficConfig.getPassword();
        String getTokenUrl=trafficConfig.getLoginUrl();
        Map<String,String> map= Maps.newHashMap();
        map.put("username",userName);
        map.put("password",password);
        try {
            String res=post(getUrl()+getTokenUrl, JSON.toJSONString(map),null);
            Result result=JSONObject.parseObject(res,Result.class);
            if (result.getCode().equals(CommonConstant.SC_OK_200))
            {
                JSONObject data= (JSONObject) result.getResult();
                return data.getString("token");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return null;
    }

    @Override
    public void saveTokenToRedis() throws Exception {
        String token=getToken();
        if (ObjectUtil.isNotEmpty(token))
        {
            redisTemplate.opsForValue().set(TOKEN_KEY,token);
        }
    }

    @Override
    public Result AddCross(JSONObject object) throws Exception {
        String token= (String) redisTemplate.opsForValue().get(TOKEN_KEY);
        if (ObjectUtil.isEmpty(token))
        {
            saveTokenToRedis();
            token= (String) redisTemplate.opsForValue().get(TOKEN_KEY);
        }
        if (ObjectUtil.isNotEmpty(token))
        {
            String addCrossUrl=trafficConfig.getAddCross();
            String url=getUrl()+addCrossUrl;
            String resule=post(url,object.toJSONString(),token);
            return Result.ok(resule);
        }
        return Result.error("BBQ了");
    }


    private String post(String url,String body,String token) throws Exception{
        //处理接收接口只支持JSONOBject
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (ObjectUtil.isNotEmpty(token))
        {
            headers.add(trafficConfig.getTokenKey(),token);
        }
        HttpEntity request1 = new HttpEntity<>(body, headers);
        log.info("请求url:{},请求头:{},请求报文：{}",url,JSON.toJSONString(headers),JSON.toJSONString(request1));

        ResponseEntity<String> jsonObjectResponseEntity = null;
        try {
            jsonObjectResponseEntity = restTemplate.postForEntity(url, request1, String.class);
        } catch (RestClientException e) {
            throw new RuntimeException(e);
        }
        String resp = jsonObjectResponseEntity.getBody();
        log.info("请求返回内容为{}",resp);
        return resp;
    }
}
